﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Email
{
    public class Smtp
    {
        private string smtpServer = "smtp.qq.com";
        private int smtpPort = 587;
        private string smtpUsername;
        private string smtpPassword;

        private string smtpSubject;
        private string smtpBody;
        private string smtpFrom;
        private string smtpTo;

        public Smtp(string smtpUsername, string smtpPassword, string smtpSubject, string smtpBody, string smtpFrom, string smtpTo)
        {
            this.smtpUsername = smtpUsername;
            this.smtpPassword = smtpPassword;
            this.smtpSubject = smtpSubject;
            this.smtpBody = smtpBody;
            this.smtpFrom = smtpFrom;
            this.smtpTo = smtpTo;
        }

        public void Send()
        {
            try
            {
                // 创建MailMessage对象
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(smtpFrom);
                mail.To.Add(smtpTo);
                mail.Subject = smtpSubject;
                mail.Body = smtpBody;

                // 创建SmtpClient对象
                SmtpClient smtpClient = new SmtpClient(smtpServer, smtpPort);
                smtpClient.Credentials = new NetworkCredential(smtpUsername, smtpPassword);
                smtpClient.EnableSsl = true; // 如果SMTP服务器需要SSL加密，设置为true

                // 发送邮件
                smtpClient.Send(mail);
                Console.WriteLine("Email sent successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to send email. Error: " + ex.Message);
            }
        }
    }
}
